package com.hroze.dao;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class CommonDaoi extends HibernateDaoSupport implements CommonDao {
	public static final Logger log = Logger.getLogger(CommonDaoi.class);

	public Object find(final String hql) {
		return this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(org.hibernate.Session session)
					throws HibernateException, SQLException {
				return session.createQuery(hql).uniqueResult();
			}

		});
	}

	public List search(String hql) {
		return this.getHibernateTemplate().find(hql);
	}

	public void delete(Object entity) {
		this.getHibernateTemplate().delete(entity);
	}

	public List search(final String hql, final Integer start,
			final Integer limit) {
		return (List) this.getHibernateTemplate().execute(
				new HibernateCallback() {
					public List doInHibernate(org.hibernate.Session session)
							throws HibernateException, SQLException {
						return session.createQuery(hql).setFirstResult(start)
								.setMaxResults(limit).list();
					}
				});
	}

	public Object findById(Class cl, Serializable id) {
		if (id == null) {
			return null;
		}
		return this.getHibernateTemplate().get(cl, id);
	}

	public void update(Object o) {
		this.getHibernateTemplate().update(o);
	}

	public void saveOrUpdate(Object o) {
		this.getHibernateTemplate().saveOrUpdate(o);
	}

	public Serializable save(Object o) {
		return this.getHibernateTemplate().save(o);
	}

	public Object getFrist(String hql) {
		List list = this.search(hql, 0, 1);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	
	public boolean executeUpdate(final String hql) {
		return (Boolean) this.getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(org.hibernate.Session session)
							throws HibernateException, SQLException {
						try {
							session.createQuery(hql).executeUpdate();
						} catch (HibernateException ex) {
							log.error("执行更新出错", ex);
							return false;
						}
						return true;
					}

				});
	}

	

	

}
